package com.woohua.demo.stream;

import cn.hutool.core.lang.Assert;
import com.woohua.demo.stream.pojo.Teacher;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @author: woo hua
 * @DATE 2022/8/8 8:36
 * @description:
 */
public class ListDemo {


    public static void main(String[] args) {
        ArrayList<Teacher> list = new ArrayList<>();
        list.add(new Teacher(1, "李"));
        list.add(new Teacher(2, "章"));
        list.add(new Teacher(3, "王"));
        list.add(new Teacher(4, "谢"));
        list.add(new Teacher(4, "李"));
        list.add(new Teacher(2, "张"));
//        List<String> collect = list.stream().map(Teacher::getName).collect(Collectors.toList());
//        System.out.println(collect);
//
//        Collections.reverse(list);
//        List<String> collect2 = list.stream().map(Teacher::getName).collect(Collectors.toList());
//        System.out.println(collect2);
//
//        list.stream().sorted(Comparator.comparing(Teacher::getId)).forEach(System.out::println);
//
//        BigDecimal bigDecimal = new BigDecimal("1.01");
//        System.out.println(bigDecimal);
//        double v = bigDecimal.doubleValue();
//        System.out.println(v);
//        String s = doubleTrans(v);
//        System.out.println(s);
//        System.out.println(new BigDecimal(s));
        Map<Integer, Teacher> collect = list.stream().collect(Collectors.toMap(Teacher::getId, v -> v, (v1, v2) -> v2));
        System.out.println(collect);

        Map<Integer, Teacher> collect1 = list.stream().filter(distinctByKey(Teacher::getId)).collect(Collectors.toMap(Teacher::getId, v -> v));

        System.out.println(collect1);
    }

    /**
     *  stream 放在 filter 中，根据指定值去重
     * @param keyExtractor 指定值
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }

    /**
     * 对double类型数据操作   忽略.0	 * @param d	 * @return
     */
    public static String doubleTrans(double d) {
        if (Math.round(d) - d == 0) {
            return String.valueOf((long) d);
        }
        return String.valueOf(d);
    }

}
